package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 查询商户列表
     * @return
     */
    @Override
    public Result queryTypeList() {
        //1.从redis中查询缓存
        List<String> list = stringRedisTemplate.opsForList().range(RedisConstants.CACHE_SHOP_LIST_KEY, 0, -1);
        //2.判断缓存是否命中
        if(list != null && list.size() > 0){
            //3.如果命中，直接返回
            List<ShopType> shopTypeList = list.stream()
                    .map(item -> JSONUtil.toBean(item, ShopType.class)).collect(Collectors.toList());
            return Result.ok(shopTypeList);
        }

        //4.如果未命中，查询数据库
        List<ShopType> shopTypeList = query().orderByAsc("sort").list();
        //5.数据库中不存在，返回错误
        if(shopTypeList == null){
            return Result.fail("商户列表不存在!");
        }
        //6.数据库中存在，写入redis
        List<String> jsonCollectionShops = shopTypeList.stream().map(JSONUtil::toJsonStr).collect(Collectors.toList());
        stringRedisTemplate.opsForList().leftPushAll(RedisConstants.CACHE_SHOP_LIST_KEY,jsonCollectionShops);
        return Result.ok(shopTypeList);
    }
}
